package com.sxt.utils;

import java.io.IOException;

import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

/**
 * fst的序列
 * @author WHSXT-LTD
 *
 */
public class FstSerializationUtils {

	private static final FSTConfiguration FST_CONF = FSTConfiguration.createDefaultConfiguration();

	/**
	 *  将对象转化为字节
	 */
	public static byte[] serialization(Object object) {
		if(object==null) {
			return new byte[0];
		}
		FSTObjectOutput objectOutput = FST_CONF.getObjectOutput();
		try {
			objectOutput.writeObject(object);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] buffer = objectOutput.getBuffer();
		int len = objectOutput.getWritten(); // 就是fst 里面写入到缓存里面的长度
		if(buffer!=null && buffer.length>0 && len>0 ) {
			// 在ArrayList 里面的扩容使用的就是它
			byte[] newBytes = new byte[len];
			System.arraycopy(buffer, 0, newBytes, 0, len);
			return newBytes ; 
		}
		return new byte[0];

	}

	/**
	 * 字节->对象
	 * @return
	 */
	public static Object deSerialization(byte[] bs) {
		if(bs==null || bs.length==0) {
			return null ;
		}
		FSTObjectInput objectInput = FST_CONF.getObjectInput(bs) ;
		Object object = null ;
		try {
			object = objectInput.readObject();
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
		return object ;
	}
//	public static void main(String[] args) {
//		TestUser testUser = new TestUser("LTD", "123456", Boolean.TRUE, new Date());
//		byte[] serialization = serialization(testUser);
//		System.out.println(serialization);
//		System.out.println(serialization.length);
//		byte[] code = JDKCoderImpl.code(testUser);
//		System.out.println(code.length);
//		TestUser user = (TestUser)deSerialization(serialization);
//		System.out.println(user);
//	}
}
